<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;

/**
 * 内容翻译模型
 */
class ContentTranslation extends Model
{
    protected $table = 'content_translations';

    protected function getOptions(): array
    {
        return [
            'autoWriteTimestamp' => true,
            'jsonAssoc'          => true,
        ];
    }

    /**
     * 关联语言模型
     */
    public function language()
    {
        return $this->belongsTo(Language::class, 'language_code', 'code');
    }

    /**
     * 获取翻译内容
     */
    public static function getTranslation($tableName, $recordId, $fieldName, $languageCode)
    {
        return self::where([
            'table_name'         => $tableName,
            'record_id'          => $recordId,
            'field_name'         => $fieldName,
            'language_code'      => $languageCode,
            'translation_status' => 1
        ])->find();
    }

    /**
     * 批量获取翻译内容
     */
    public static function batchGetTranslations($tableName, $recordIds, $languageCode)
    {
        if (empty($recordIds)) {
            return [];
        }

        return self::where([
            'table_name'         => $tableName,
            'language_code'      => $languageCode,
            'translation_status' => 1
        ])->whereIn('record_id', $recordIds)
            ->select()
            ->toArray();
    }

    /**
     * 保存或更新翻译
     */
    public static function saveTranslation(
        $tableName,
        $recordId,
        $fieldName,
        $languageCode,
        $originalContent,
        $translatedContent,
        $translateApi = null,
        $status = 1,
        $errorMessage = null
    ) {
        $data = [
            'original_content'   => $originalContent,
            'translated_content' => $translatedContent,
            'translation_status' => $status,
            'is_auto_translated' => $translateApi ? 1 : 0,
            'translate_api'      => $translateApi,
            'error_message'      => $errorMessage
        ];

        return self::updateOrCreate([
            'table_name'    => $tableName,
            'record_id'     => $recordId,
            'field_name'    => $fieldName,
            'language_code' => $languageCode,
        ], $data);
    }

    /**
     * 获取翻译统计
     */
    public static function getTranslationStats()
    {
        $stats = [
            'total'      => self::count(),
            'translated' => self::where('translation_status', 1)->count(),
            'pending'    => self::where('translation_status', 0)->count(),
            'failed'     => self::where('translation_status', 2)->count(),
        ];

        $stats['success_rate'] = $stats['total'] > 0
            ? round($stats['translated'] / $stats['total'] * 100, 2)
            : 0;

        return $stats;
    }

    /**
     * 获取按表名分组的统计
     */
    public static function getStatsByTable()
    {
        return self::field('table_name, translation_status, count(*) as count')
            ->group('table_name, translation_status')
            ->select()
            ->toArray();
    }

    /**
     * 获取按语言分组的统计
     */
    public static function getStatsByLanguage()
    {
        return self::field('language_code, translation_status, count(*) as count')
            ->group('language_code, translation_status')
            ->select()
            ->toArray();
    }

    /**
     * 清理失败的翻译记录
     */
    public static function cleanFailedTranslations($days = 7)
    {
        return self::where('translation_status', 2)
            ->where('created_at', '<', date('Y-m-d H:i:s', strtotime("-{$days} days")))
            ->delete();
    }
}
